package cn.yogehaoren.handler;

import cn.yogehaoren.main.StartProxyServerApp;
import com.haojiangbo.model.EventMessage;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpObject;
import io.netty.handler.codec.http.HttpRequest;

import java.nio.charset.StandardCharsets;

import static io.netty.handler.codec.http.HttpResponseStatus.OK;
import static io.netty.handler.codec.http.HttpVersion.HTTP_1_1;

/**
 * @author WangNing yogehaoren@gamil.com <br>
 * @since 1.0
 */
public class HttpManagerHandler extends SimpleChannelInboundHandler<HttpObject> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception {

        if(msg instanceof HttpRequest){

            HttpRequest request = (HttpRequest) msg;

            String requestPath = request.uri();

            if(requestPath.equals("/api/v3/reload")){
                handleReload(ctx);
            }
        }

    }

    private void handleReload(ChannelHandlerContext ctx){

        EventMessage eventMessage = new EventMessage();
        eventMessage.setType(EventMessage.RELOAD_EVENT);
        StartProxyServerApp.getInstance().notifyEvent(eventMessage);

        FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK, Unpooled.wrappedBuffer("OK!".getBytes(StandardCharsets.UTF_8)));
        ctx.writeAndFlush(response);

    }
}
